<?php

namespace app\services;

use plugin\admin\app\model\UserBankCard;
use support\BankCard;

class UserBankCardService
{
    public static function edit($id, $data)
    {
        $data['number'] = str_replace(' ', '', $data['number']);

        $existingCard = UserBankCard::where('number', $data['number'])->where('id', '!=', $id)->first();
        if ($existingCard) {
            throw new \Exception('银行卡已被其他人绑定');
        }

        $appcode = getenv('BANK_CARD_APPCODE');
        if (!$appcode) {
            throw new \Exception('系统错误，请联系管理员');
        }

        if (getenv('APP_DEBUG')) {
            $result = [
                'code' => 0,
                'data' => [
                    'cardType' => '储蓄卡',
                    'bankLogo' => ''
                ]
            ];
        } else {
            $result = (new BankCard($appcode))->auth($data['number'], $data['name'], $data['idcard']);
        }

        if ($result['code'] == 0) {
            $data['card_type'] = $result['data']['cardType'];
            $data['logo'] = $result['data']['bankLogo'];
        } else {
            throw new \Exception($result['desc']);
        }

        UserBankCard::where('id', $id)->where('user_id', get_user_id())->update($data);
    }

    public static function add($data)
    {
        $data['user_id'] = get_user_id();
        $data['number'] = str_replace(' ', '', $data['number']);
        $data['created_time'] = date('Y-m-d H:i:s');

        if (UserBankCard::where('number', $data['number'])->count() > 0) {
            throw new \Exception('银行卡已被其他人绑定');
        }

        $appcode = getenv('BANK_CARD_APPCODE');

        if (!$appcode) {
            throw new \Exception('系统错误，请联系管理员');
        }

        if (getenv('APP_DEBUG')) {
            $result = [
                'code' => 0,
                'data' => [
                    'cardType' => '储蓄卡',
                    'bankLogo' => ''
                ]
            ];
        } else {
            $result = (new BankCard($appcode))->auth($data['number'], $data['name'], $data['idcard']);
        }

        if ($result['code'] == 0) {
            $data['card_type'] = $result['data']['cardType'];
            $data['logo'] = $result['data']['bankLogo'];
        } else {
            throw new \Exception($result['desc']);
        }

        UserBankCard::insert($data);
    }

    public static function delete($id)
    {
        UserBankCard::where('id', $id)->where('user_id', get_user_id())->delete();
    }

    public static function list()
    {
        $bankCardList = UserBankCard::select(['id', 'card_type', 'logo', 'number', 'bank_name'])->where('user_id', get_user_id())->get()->toArray();

        foreach ($bankCardList as $key=>$item) {
            $bankCardList[$key]['number'] = format_bank_card($item['number']);
        }

        return $bankCardList;
    }
}